package com.yunhe.video.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yunhe.video.VideoServerApplication;
import com.yunhe.video.domain.ControlVideo;
import com.yunhe.video.domain.ResponseJson;
import com.yunhe.video.domain.SrcJson;
import com.yunhe.video.domain.VideoResult;
import com.yunhe.video.service.IVideoService;
import com.yunhe.video.utils.HkvsSdk;
import com.yunhe.video.utils.YmlUtils;
import com.yunhe.common.util.CollectionUtil;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jettison.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author: DongWenYu
 * @Date: 2021/3/8 13:44
 */
@Service
public class VideoServiceImpl implements IVideoService {

    private static final String TOPIC = "VideoOperateQueue";

    private static final String URL = "https://video.yunqilaohe.com/live?port=1935&app=live&stream=robot";
    private static final String CAGYY_URL = "https://video-cagyy.yunqilaohe.com:8443/live?port=1935&app=live&stream=robot";
    private static final String CLIENT_URL = "https://192.168.0.82/live?port=1935&app=live&stream=robot";

    private static final Logger log = LoggerFactory.getLogger(VideoServiceImpl.class);

    private static final String IP_ADDRESS_PRE = "192.168.5.";

    private static HashMap videoCodeMap = new HashMap();

    @Value("${videoCode.path}")
    private String videoCodePath;

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Override
    public VideoResult sendCommand(String operateVideo , String command) {
        String message = command +"_" + operateVideo;
        log.info("topic:{},message:{}",TOPIC,message);
        kafkaTemplate.send(TOPIC,message);
        VideoResult videoResult = new VideoResult();
//        videoResult.setRemoteUrl(URL+operateVideo);
        videoResult.setRemoteUrl(CAGYY_URL+operateVideo);
        videoResult.setClientUrl(CLIENT_URL+operateVideo);
        return videoResult;
    }

    @Override
    public void operateVideo(String operateVideo, String command, String action, String speed) throws FileNotFoundException, JSONException {
        ControlVideo controlVideo = new ControlVideo();
        controlVideo.setCommand(command);
        Optional.ofNullable(action).ifPresent(controlVideo::setAction);
        Optional.ofNullable(speed).ifPresent(controlVideo::setSpeed);
        log.info("需要操作的摄像头ip地址为：" + IP_ADDRESS_PRE + operateVideo);
        String videoCode = (String) videoCodeMap.get(IP_ADDRESS_PRE + operateVideo);
        //判断内存中是否有缓存
        if (StringUtils.isEmpty(videoCode)) {
            videoCodeMap = YmlUtils.getYmlByFileName(videoCodePath);
            videoCode = (String) videoCodeMap.get(IP_ADDRESS_PRE + operateVideo);
            //这边要判断是不是在yml中
            if (StringUtils.isEmpty(videoCode)) {
                HkvsSdkControlVideo(videoCode, controlVideo);
            }
        } else {
            HkvsSdkControlVideo(videoCode, controlVideo);
        }
    }

    private void HkvsSdkControlVideo(String videoCode, ControlVideo controlVideo) throws JSONException {
        log.info("需要操作的摄像头编码为：" + videoCode);
        controlVideo.setCameraId(videoCode);
        HkvsSdk.controlVideo(controlVideo.getCameraId(), controlVideo.getCommand(),
                controlVideo.getAction(), controlVideo.getSpeed());
    }

    /**
     * 解析文件
     * @return
     */
    private static ResponseJson resolveJsonFileForMe() {
        String jsonStr = "";
        try {
            File jsonFile = ResourceUtils.getFile("D:/json.txt");
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
            int ch = 0;
            StringBuilder sb = new StringBuilder();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            ResponseJson responseJson = JSON.toJavaObject(JSONObject.parseObject(jsonStr), ResponseJson.class);
            System.out.println(responseJson);
            creatYml(responseJson);
            return responseJson;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 创建yml
     * @param responseJson
     * @throws IOException
     */
    private static void creatYml(ResponseJson responseJson) throws IOException {
        System.out.println("creatYml.......");
        List<SrcJson> srcJsonList = responseJson.getSource().getSrc();
        if (CollectionUtil.isNotEmpty(srcJsonList)) {
            Map<String, String> root = srcJsonList.stream().collect(
                    Collectors.toMap(SrcJson::getStrSrcIpAddress, SrcJson::getStrToken)
            );

            // 写入Yaml
            DumperOptions dumperOptions = new DumperOptions();
            dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
            Yaml yaml = new Yaml(dumperOptions);
            File dumpFile = new File("D:/ideaProjects/yh-cloudSPO-service/yh-video/src/main/resources/conf/videoCode.yml");
            FileWriter fileWriter = new FileWriter(dumpFile);
            yaml.dump(root, fileWriter);
            fileWriter.close();
        }

    }

//    @KafkaListener(topics = {TOPIC})
//    @Override
//    public void receive(String message ) {
//    }
}
